package com.coffee.wx.uitls.wx;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.coffee.wx.uitls.SendHttpUtils;
import com.coffee.wx.uitls.TokenUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 微信公众号信息
 */
public class WxSendMsgUtils {

    static final String URL_PREFIX = "https://api.weixin.qq.com/cgi-bin";

    // 发送模板消息
    static final String SEND_TEMPLATE_MSG_URL_PATH = "/message/template/send?access_token=%s";


    /**
     * 好友助力成功
     *
     * @param openId    消息接受者openId
     * @param userName  助力用户名称
     * @param number    当前助力值
     * @param grade     当前等级
     * @param remaining 下一等级还需助力数
     * @return true 消息发送成功，false 消息发送失败
     */
    public static boolean successfullyAssisted(String openId, String userName, Long number, String grade, String remaining) {
        String templateId = "X0NGAhxMcyYwmbhn8VVCq8K9QkUSRS_7mqUKixv3KP8";
        Map<String, String> data = new HashMap<>();
        data.put("name", userName);
        data.put("date", DateUtil.now());
        data.put("number", String.valueOf(number));
        data.put("grade", grade);
        data.put("remaining", remaining);

        return sendTemplateMsg(data, templateId, openId);
    }


    /**
     * 发送模板消息
     *
     * @param data
     * @param templateId
     * @param openId
     * @return
     */
    public static boolean sendTemplateMsg(Map<String, String> data, String templateId, String openId) {
        Map<String, Object> params = new HashMap<>();
        params.put("touser", openId);
        params.put("template_id", templateId);
        params.put("data", buildMsgData(data));

        String response = SendHttpUtils.doPost(
                String.format(URL_PREFIX + SEND_TEMPLATE_MSG_URL_PATH, TokenUtils.getAccessToken()),
                params);
        Map responseMap = JSONUtil.parse(response).toBean(Map.class);
        Console.log(" responseMap ====> " + responseMap);
        String errcode = MapUtil.getStr(responseMap, "errcode");
        return "0".equals(errcode);
    }

    /**
     * 构建消息体
     *
     * @return
     */
    private static Map<String, Object> buildMsgData(Map<String, String> data) {

        Map<String, Object> resultMap = new HashMap<>();
        Set<String> strings = data.keySet();
        for (String key : strings) {
            String value = data.get(key);
            resultMap.put(key, MapUtil.builder(new HashMap<String, String>())
                    .put("value", value)
                    .put("color", "#D7696C").build());
        }

        return resultMap;
    }
}
